import { Tooltip } from 'antd'
import { Component } from 'react'

import styles from './index.module.less'

const isSupportLineClamp = document.body.style.webkitLineClamp !== undefined

const EllipsisText = ({ text, length, tooltip, ...other }) => {
  if (typeof text !== 'string') {
    throw new Error('Ellipsis children must be string.')
  }
  if (text.length <= length || length < 0) {
    return <span {...other}>{text}</span>
  }
  const tail = '...'
  let displayText = text.slice(0, length)

  if (tooltip) {
    return (
      <Tooltip title={text}>
        <span>
          {displayText}
          {tail}
        </span>
      </Tooltip>
    )
  }

  return (
    <span {...other}>
      {displayText}
      {tail}
    </span>
  )
}

/**
 * @typedef {Object} EllipsisProps
 * @property {number} [lines] 在按照行数截取下最大的行数，超过则截取省略，默认1行
 * @property {number} [length] 在按照长度截取下的文本最大字符数，超过则截取省略
 * @property {boolean} [tooltip] 移动到文本是否展示完整内容的提示，默认true
 */

class EllipsisA extends Component {
  state = {
    text: '',
    targetCount: 0,
  }

  componentDidMount() {
    if (this.node) {
      this.computeLine()
    }
  }

  // eslint-disable-next-line camelcase
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.lines !== nextProps.lines) {
      this.computeLine()
    }
  }

  computeLine = () => {
    const { lines } = this.props
    if (lines && !isSupportLineClamp) {
      const text = this.shadowChildren.innerText
      const lineHeight = parseInt(getComputedStyle(this.root).lineHeight, 10)
      const targetHeight = lines * lineHeight
      this.content.style.height = `${targetHeight}px`
      const totalHeight = this.shadowChildren.offsetHeight
      const shadowNode = this.shadow.firstChild

      if (totalHeight <= targetHeight) {
        this.setState({
          text,
          targetCount: text.length,
        })
        return
      }

      // bisection
      const len = text.length
      const mid = Math.floor(len / 2)

      const count = this.bisection(targetHeight, mid, 0, len, text, shadowNode)

      this.setState({
        text,
        targetCount: count,
      })
    }
  }

  bisection = (th, m, b, e, text, shadowNode) => {
    const suffix = '...'
    let mid = m
    let end = e
    let begin = b
    shadowNode.innerHTML = text.substring(0, mid) + suffix
    let sh = shadowNode.offsetHeight

    if (sh <= th) {
      shadowNode.innerHTML = text.substring(0, mid + 1) + suffix
      sh = shadowNode.offsetHeight
      if (sh > th) {
        return mid
      }
      begin = mid
      mid = Math.floor((end - begin) / 2) + begin
      return this.bisection(th, mid, begin, end, text, shadowNode)
    }
    if (mid - 1 < 0) {
      return mid
    }
    shadowNode.innerHTML = text.substring(0, mid - 1) + suffix
    sh = shadowNode.offsetHeight
    if (sh <= th) {
      return mid - 1
    }
    end = mid
    mid = Math.floor((end - begin) / 2) + begin
    return this.bisection(th, mid, begin, end, text, shadowNode)
  }

  handleRoot = n => {
    this.root = n
  }

  handleContent = n => {
    this.content = n
  }

  handleNode = n => {
    this.node = n
  }

  handleShadow = n => {
    this.shadow = n
  }

  handleShadowChildren = n => {
    this.shadowChildren = n
  }

  render() {
    const { text, targetCount } = this.state
    const { children, lines, length, className, tooltip, ...restProps } = this.props

    const cls = `${styles.ellipsis} ${className || ''} ${lines && isSupportLineClamp ? styles.lineClamp : styles.lines}`

    if (!lines && !length) {
      return (
        <span className={cls} {...restProps}>
          {children}
        </span>
      )
    }

    // length
    if (!lines) {
      return <EllipsisText className={cls} length={length} text={children || ''} tooltip={tooltip} {...restProps} />
    }

    const id = `antd-pro-ellipsis-${`${new Date().getTime()}${Math.floor(Math.random() * 100)}`}`

    // support document.body.style.webkitLineClamp
    if (isSupportLineClamp) {
      const style = `#${id}{-webkit-line-clamp:${lines};}`
      return (
        <div id={id} className={cls} {...restProps}>
          <style>{style}</style>
          {tooltip ? <Tooltip title={text || children}>{children}</Tooltip> : children}
        </div>
      )
    }

    const childNode = (
      <span ref={this.handleNode}>
        {targetCount > 0 && text.substring(0, targetCount)}
        {targetCount > 0 && targetCount < text.length && '...'}
      </span>
    )

    return (
      <div {...restProps} ref={this.handleRoot} className={cls}>
        <div ref={this.handleContent}>
          {tooltip ? <Tooltip title={text}>{childNode}</Tooltip> : childNode}
          <div className={styles.shadow} ref={this.handleShadowChildren}>
            {children}
          </div>
          <div className={styles.shadow} ref={this.handleShadow}>
            <span>{text}</span>
          </div>
        </div>
      </div>
    )
  }
}

/**
 * 超出省略组件
 * @param {EllipsisProps} props
 * @returns
 */
const Ellipsis = props => {
  const { lines = 1, tooltip = true, ...other } = props
  return <EllipsisA {...{ lines, tooltip, ...other }} />
}

export default Ellipsis
